/*
 * JANN - a Java toolkit for creating arbitrary Artificial Neural Networks.
 * 
 * Copyright (c) 2009 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.jann;

public class Link extends NeuralElement {

	private static final long serialVersionUID = -9015980394895195411L;
	
	protected Neuron preNeuron, postNeuron;
	
	public Link() {
		super();
	}
	
	public Link( Neuron in, Neuron out ) {
		this();
		setPreNeuron(in);
		setPostNeuron(out);
	}
	
	public Neuron getPostNeuron() {
		return postNeuron;
	}

	public void setPostNeuron(Neuron n) {
		if ( postNeuron == n )
			return;
		if ( postNeuron != null )
			postNeuron.removeInputLink(this);
		postNeuron = n;
		if ( postNeuron != null )
			postNeuron.addInputLink(this);
	}

	public Neuron getPreNeuron() {
		return preNeuron;
	}

	public void setPreNeuron(Neuron n) {
		if ( preNeuron == n )
			return;
		if ( preNeuron != null )
			preNeuron.removeOutputLink(this);
		preNeuron = n;
		if ( preNeuron != null )
			preNeuron.addOutputLink(this);
	}
	
	@Override
	public void backProp( double delta ) {
		//For LINK essential to FIRST propagate and THEN update, because the neuron needs
		//the CURRENT weight for its calculation of its contribution to the error
		preNeuron.backProp( weight * delta );
		updateWeight( delta );
	}
	
	@Override
	public void feedForward( double input ) {
		postNeuron.feedForward( weight * input );
	}
	
	@Override
	protected double getSendingActivation() {
		return preNeuron.getActivation();
	}
}
